package com.sunday.pinxinghui.model.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sunday.common.base.BaseFragment;
import com.sunday.common.event.EventBus;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.StringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.adapter.CartAdapter;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.entity.CartConfirm;
import com.sunday.pinxinghui.entity.CartItem;
import com.sunday.pinxinghui.event.UpdateCartNum;
import com.sunday.pinxinghui.model.order.OrderConfirmActivity;
import com.sunday.pinxinghui.model.products.ProductDetailActivity;
import com.sunday.pinxinghui.network.ApiClient;
import com.sunday.pinxinghui.widgets.ProductWindow;
import com.sunday.pinxinghui.widgets.UpdateCartNumWindow;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sunday.pinxinghui.R.id.rightTxt;
import static com.sunday.pinxinghui.R.id.tvNum2;
import static com.umeng.analytics.pro.x.S;

/**
 * Created by 刘涛 on 2017/8/3.
 */

public class CartFragment extends BaseFragment {


    @Bind(R.id.left_btn)
    ImageView leftBtn;
    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.checkbox_select_all)
    CheckBox checkboxSelectAll;
    @Bind(R.id.btn_buy)
    TextView btnBuy;
    @Bind(R.id.total_money)
    TextView totalMoney;
    @Bind(R.id.text_total_money)
    TextView textTotalMoney;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;


    private boolean isFromDetail;
    private long memberId;
    private CartAdapter adapter;
    private List<CartItem> dataSet = new ArrayList<>();
    private boolean selectAll = true;//是否全选

    private UpdateCartNumWindow updateCartWindow;


    public static CartFragment newInstance(boolean isFromDetail) {
        CartFragment fragment = new CartFragment();
        Bundle args = new Bundle();
        args.putBoolean("isFromDetail", isFromDetail);
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_cart, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            isFromDetail = getArguments().getBoolean("isFromDetail");
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        memberId = BaseApplication.getInstance().getMember().getId();
        // memberId = Constants.TEST_MEMBERID;
        //EventBus.getDefault().register(this);
        initView();
        getData();

    }

    private void initView() {
        titleView.setText("购物车");
        if (!isFromDetail) {
            leftBtn.setVisibility(View.GONE);
        }
        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.getItemAnimator().setChangeDuration(0);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).drawable(R.drawable.shape_divider).build());
        adapter = new CartAdapter(mContext, dataSet);
        recyclerView.setAdapter(adapter);
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getData();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });
        adapter.setOnClickListener(onClickListener);


        checkboxSelectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    selectAll = true;
                    if (dataSet != null && dataSet.size() > 0) {
                        for (int i = 0; i < dataSet.size(); i++) {
                            dataSet.get(i).setSelect(selectAll);
                        }
                    }
                } else {
                    selectAll = false;
                    int selectNum = 0;
                    for (CartItem cartItem : dataSet) {
                        if (cartItem.isSelect()) {
                            selectNum += 1;
                        }
                    }
                    if (selectNum == dataSet.size()) {
                        if (dataSet != null && dataSet.size() > 0) {
                            for (int i = 0; i < dataSet.size(); i++) {
                                dataSet.get(i).setSelect(false);
                            }
                        }
                    }
                }
                updatePrice();
                adapter.notifyDataSetChanged();
            }
        });
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getData();
            }
        });
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final int p = (int) v.getTag();
            int num = dataSet.get(p).getNum();
            CartItem cartItem = dataSet.get(p);
            switch (v.getId()) {
                case R.id.ivCheckGood:
                    dataSet.get(p).setSelect(!dataSet.get(p).isSelect());
                    adapter.notifyItemChanged(p);
                    if (selectAll) {
                        selectAll = !selectAll;
                        checkboxSelectAll.setChecked(false);
                    } else {
                        //判断是否全选 同时更新结算
                        int totalNum = 0;
                        for (CartItem item : dataSet) {
                            if (item.isSelect()) {
                                totalNum++;
                            }
                        }
                        if (totalNum == dataSet.size()) {
                            selectAll = true;
                            checkboxSelectAll.setChecked(true);
                        }
                    }
                    updatePrice();
                    break;
                case R.id.ivAdd:
                    num++;
                    dataSet.get(p).setNum(num);
                    adapter.notifyItemChanged(p);
                    updateCart(p, "1");
                    break;
                case R.id.ivReduce:
                    if (num > 1) {
                        num--;
                        dataSet.get(p).setNum(num);
                        adapter.notifyItemChanged(p);
                        updateCart(p, "-1");
                    }
                    break;
                case R.id.delete:
                    final UIAlertView alertView = new UIAlertView(mContext, "温馨提示", "确认删除吗", "取消", "确定");
                    alertView.show();
                    alertView.setClicklistener(new UIAlertView.ClickListenerInterface() {
                        @Override
                        public void doLeft() {
                            alertView.dismiss();
                        }

                        @Override
                        public void doRight() {
                            deleteCart(p);
                            alertView.dismiss();
                        }
                    });
                    break;
                case R.id.rl_cartItem:
                    Intent intent = new Intent(mContext, ProductDetailActivity.class);
                    intent.putExtra("productId", cartItem.getProductId());
                    startActivity(intent);
                    break;
                case R.id.tvNum2:
                    updateCartWindow = new UpdateCartNumWindow(mContext, click, num, p);
                    updateCartWindow.showPopupWindow(btnBuy);
                    break;
            }
        }
    };

    private UpdateCartNumWindow.Click click = new UpdateCartNumWindow.Click() {
        @Override
        public void click(int originNum, int num, int p) {
            if (num != 0) {
                updateCart(p, String.valueOf(num));
                dataSet.get(p).setNum(num + originNum);
                adapter.notifyDataSetChanged();
            }
        }
    };


    @OnClick({R.id.btn_buy})
    void onClick() {
        //购物车结算
        countCart();
    }

    private void countCart() {
        final List<String> cartIds = new ArrayList<>();
        for (CartItem item : dataSet) {
            if (item.isSelect()) {
                cartIds.add(String.valueOf(item.getCarId()));
            }
        }
        showLoadingDialog(0);
        Call<ResultDO<CartConfirm>> call = ApiClient.getApiAdapter().countCart(StringUtils.listToString(cartIds),
                memberId);
        call.enqueue(new Callback<ResultDO<CartConfirm>>() {
            @Override
            public void onResponse(Call<ResultDO<CartConfirm>> call, Response<ResultDO<CartConfirm>> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    Intent intent = new Intent(mContext, OrderConfirmActivity.class);
                    intent.putExtra("orderConfirm", response.body().getResult());
                    intent.putExtra("catIds", StringUtils.listToString(cartIds));
                    mContext.startActivity(intent);
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<CartConfirm>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });

    }

    private void getData() {
        showLoadingDialog(0);
        Call<ResultDO<List<CartItem>>> call = ApiClient.getApiAdapter().getCarts(memberId);
        call.enqueue(new Callback<ResultDO<List<CartItem>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<CartItem>>> call, Response<ResultDO<List<CartItem>>> response) {
                dissMissDialog();
                ptrFrame.refreshComplete();
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    dataSet.clear();
                    if (response.body().getResult() != null) {
                        dataSet.addAll(response.body().getResult());
                    }
                    if (dataSet.size() > 0) {
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }
                   /* for (int i = 0; i < dataSet.size(); i++) {
                        dataSet.get(i).setSelect(true);
                    }
                    checkboxSelectAll.setChecked(true);*/
                    adapter.notifyDataSetChanged();
                    updatePrice();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<CartItem>>> call, Throwable t) {
                dissMissDialog();
                ptrFrame.refreshComplete();
            }
        });
    }


    private BigDecimal countMoney = BigDecimal.ZERO;

    //更新结算
    private void updatePrice() {
        BigDecimal total_money = BigDecimal.ZERO;
        for (CartItem cartItem : dataSet) {
            if (cartItem.isSelect()) {
                total_money = total_money.add(cartItem.getPrice().multiply(BigDecimal.valueOf(cartItem.getNum())));
            }
        }
        countMoney = total_money;
        totalMoney.setText(String.format("¥%s", countMoney.setScale(2, RoundingMode.HALF_UP)));
    }

    //更新购物项的单个数量
    public void updateCart(final int position, String num) {
        long cartId = dataSet.get(position).getCarId();
        showLoadingDialog(0);
        Call<ResultDO> call = ApiClient.getApiAdapter().updateNum(cartId, num);
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                dissMissDialog();
                ResultDO resultDO = response.body();
                if (isFinish || resultDO == null) {
                    return;
                }
                if (resultDO.getCode() == 0) {
                    //如果是选中的数量有变化重新结算
                    if (dataSet.get(position).isSelect()) {
                        updatePrice();
                    }
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, "网络连接错误");
            }
        });

    }

    private void deleteCart(final int p) {
        long cartId = dataSet.get(p).getCarId();
        showLoadingDialog(0);
        showLoadingDialog(0);
        Call<ResultDO> call = ApiClient.getApiAdapter().deleteCart(String.valueOf(cartId));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    getData();
                    EventBus.getDefault().post(new UpdateCartNum());
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, "网络连接错误");
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()) {
            getData();
        }
    }
}
